package com.ruoyix.alipay.service.impl;

import cn.hutool.json.JSONObject;
import com.ruoyix.alipay.config.AliPayConfig;
import com.ruoyix.alipay.domain.AliPay;
import com.ruoyix.alipay.service.AliPayService;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import cn.hutool.json.JSONUtil;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.alipay.easysdk.factory.Factory;

import org.jetbrains.annotations.NotNull;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class AliPayServiceImpl implements AliPayService {

    @Resource
    AliPayConfig aliPayConfig;

    private static final String GATEWAY_URL ="https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT ="JSON";
    private static final String CHARSET ="utf-8";
    private static final String SIGN_TYPE ="RSA2";

    @Override
    public void pcPay(AliPay aliPay, HttpServletResponse httpResponse) throws IOException {
        AlipayClient alipayClient = getAlipayClient();
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setReturnUrl(aliPayConfig.getReturnUrl());
        request.setBizContent("{\"out_trade_no\":\"" + aliPay.getOutTradeNo() + "\","
            + "\"total_amount\":\"" + aliPay.getTotalAmount() + "\","
            + "\"subject\":\"" + aliPay.getSubject() + "\","
            + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        // 直接将完整的表单html输出到页面
        httpResponse.getWriter().write(form);
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    @Override
    public String payQrCode(AliPay aliPay, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AlipayApiException {
        AlipayClient alipayClient = getAlipayClient();
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        model.setOutTradeNo(aliPay.getOutTradeNo());
        model.setTotalAmount(aliPay.getTotalAmount());
        model.setSubject(aliPay.getSubject());
        request.setBizModel(model);
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setReturnUrl(aliPayConfig.getReturnUrl());
        com.alipay.api.response.AlipayTradePrecreateResponse response = alipayClient.execute(request);
        System.out.println(response.getBody());
        JSONObject jsonObject =  JSONUtil.parseObj(response.getBody());
        String qrUrl = jsonObject.getJSONObject("alipay_trade_precreate_response").get("qr_code").toString();
//        QrCodeUtil.generate(qrUrl, 300, 300, "png", httpServletResponse.getOutputStream());
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return  qrUrl;
    }

    @Override
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");
            String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no");
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
                System.out.println("交易名称: " + params.get("subject"));
                System.out.println("交易状态: " + params.get("trade_status"));
                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
                System.out.println("商户订单号: " + params.get("out_trade_no"));
                System.out.println("交易金额: " + params.get("total_amount"));
                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
                System.out.println("买家付款时间: " + params.get("gmt_payment"));
                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));
                // 更新订单已支付的逻辑代码
            }
        }
        return "success";
    }

    @Override
    public JSONObject queryTrade(AliPay aliPay) throws AlipayApiException {
        AlipayClient alipayClient = getAlipayClient();
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        AlipayTradeQueryModel model = new AlipayTradeQueryModel();
        model.setOutTradeNo(aliPay.getOutTradeNo());
        model.setTradeNo(aliPay.getTraceNo());
        request.setBizModel(model);
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        return JSONUtil.parseObj(response.getBody());
    }

    @Override
    public JSONObject TradeRefund(AliPay aliPay) throws AlipayApiException {
        AlipayClient alipayClient = getAlipayClient();
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        AlipayTradeRefundModel model = new AlipayTradeRefundModel();
        model.setOutTradeNo(aliPay.getOutTradeNo());
        model.setTradeNo(aliPay.getTraceNo());
        model.setRefundAmount(aliPay.getTotalAmount());
        model.setOutRequestNo(aliPay.getOutRequestNo());
        request.setBizModel(model);
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        return JSONUtil.parseObj(response.getBody());
    }

    @NotNull
    private AlipayClient getAlipayClient() {
        return new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
            aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
    }
}
